<template>
  <div>
      <div class="head-container">
        <el-input
          v-model="deptName"
          placeholder="请输入部门名称"
          clearable
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container">
        <el-tree
          :data="deptOptions"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          show-checkbox
          default-expand-all
          @check="handleNodeClick"
        />
      </div>
  </div>
</template>

<script setup name="FlowDept">
import { deptTreeSelect } from "@/api/system/user";
import {markRaw} from "@vue/reactivity";
import {StrUtil} from "@/utils/StrUtil";

const router = useRouter();
const { proxy } = getCurrentInstance();

const loading = ref(true);
const showSearch = ref(true);
const deptName = ref("");
const deptOptions = ref(undefined);

const emit = defineEmits(['handleAssignSelect'])

/** 组件传值  */
const props = defineProps({
  // 回显数据传值
  selectData: {
    type: String,
    default: null,
    required: false
  },
});

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    proxy.$nextTick(() => {
      // 打开时回显数据
      echoChooseItems();
    });
  });
}

// 回显（勾选）已选事项
function echoChooseItems() {
  if (StrUtil.isNotBlank(props.selectData)){
    if (deptOptions.value.length > 0) {
      // 通过 keys 设置目前勾选的节点，使用此方法必须设置 node-key 属性
      proxy.$refs.tree.setCheckedKeys(props.selectData.split(","));
    }
  }
}

/** 节点选中事件 */
function handleNodeClick(data,node) {
  emit('handleAssignSelect', markRaw(node.checkedNodes));
}

getDeptTree();
</script>

